// Package sys
// @Link  https://github.com/bufanyun/hotgo
// @Copyright  Copyright (c) 2024 HotGo CLI
// @Author  Ms <133814250@qq.com>
// @License  https://github.com/bufanyun/hotgo/blob/master/LICENSE
// @AutoGenerate Version 2.13.1
package sys

import (
	"context"
	"hotgo/api/admin/stockrank"
	"hotgo/internal/model/input/sysin"
	"hotgo/internal/service"
	"slices"
)

var (
	StockRank = cStockRank{}
)

type cStockRank struct{}

// List 查看人气榜列表
func (c *cStockRank) List(ctx context.Context, req *stockrank.ListReq) (res *stockrank.ListRes, err error) {
	list, _, err := service.SysStockRank().List(ctx, &req.StockRankListInp)
	if err != nil {
		return
	}

	if list == nil {
		list = []*sysin.StockRankListModel{}
	}
	var rankMap = make(map[string][]*sysin.StockRankListModel)
	for _, rankListModel := range list {
		rankMap[rankListModel.Source] = append(rankMap[rankListModel.Source], rankListModel)
	}
	res = new(stockrank.ListRes)
	var items []*stockrank.ListItem
	for source, models := range rankMap {
		slices.SortFunc(models, func(a, b *sysin.StockRankListModel) int {
			return a.Rank - b.Rank
		})
		if len(models) > 50 {
			models = models[:50]
		}
		items = append(items, &stockrank.ListItem{
			Source: source,
			List:   models,
		})
	}
	slices.SortFunc(items, func(a, b *stockrank.ListItem) int {
		sourceScore := map[string]int{
			"开盘啦":    1,
			"东财-飙升榜": 2,
			"东财-人气榜": 3,
			"百度热搜股":  4,
		}
		aSource := sourceScore[a.Source]
		bSource := sourceScore[b.Source]

		return aSource - bSource
	})
	res.Items = items
	return
}

// Export 导出人气榜列表
func (c *cStockRank) Export(ctx context.Context, req *stockrank.ExportReq) (res *stockrank.ExportRes, err error) {
	err = service.SysStockRank().Export(ctx, &req.StockRankListInp)
	return
}

// Edit 更新人气榜
func (c *cStockRank) Edit(ctx context.Context, req *stockrank.EditReq) (res *stockrank.EditRes, err error) {
	err = service.SysStockRank().Edit(ctx, &req.StockRankEditInp)
	return
}

// View 获取指定人气榜信息
func (c *cStockRank) View(ctx context.Context, req *stockrank.ViewReq) (res *stockrank.ViewRes, err error) {
	data, err := service.SysStockRank().View(ctx, &req.StockRankViewInp)
	if err != nil {
		return
	}

	res = new(stockrank.ViewRes)
	res.StockRankViewModel = data
	return
}

// Delete 删除人气榜
func (c *cStockRank) Delete(ctx context.Context, req *stockrank.DeleteReq) (res *stockrank.DeleteRes, err error) {
	err = service.SysStockRank().Delete(ctx, &req.StockRankDeleteInp)
	return
}
